package com.cavy.platform.server;

import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import java.util.ArrayList;
import java.util.List;

/**
 * json数据统一返回为此格式
 */
@Data
@Accessors(chain = true)
public class ResultInfo {
    private Object data;
    private boolean success = true;
    private List<ErrorItem> errors = new ArrayList<>();

    public ResultInfo(Object returnValue) {
        this.data = returnValue;
    }

    public static ResultInfo newSuccess() {
        return new ResultInfo(null);
    }

    @Data
    public class ErrorItem {
        private String field;
        private String message;

        public ErrorItem(String message) {
            this.message = message;
        }

        public ErrorItem(ObjectError error) {
            if (error instanceof FieldError) {
                this.field = ((FieldError) error).getField();
            }
            this.message = error.getDefaultMessage();
        }
    }
}
